package com.eds.ailipay.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.eds.pojo.BaseResult;
import com.eds.pojo.CodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName：AlipayController
 * @Author: caiyuaan
 * @Date: 2024/11/05
 * @Description: 支付宝审核侧就那个QR码
 */
@RestController
@RequestMapping("/payController")
public class AlipayController {
    @Autowired
    AlipayClient alipayClient;
    @Value("${alipay.publicKey}")
    private String publicKey;

    /* *
     * @Title: createNative
     * @Author: vvSmile
     * @Date: 2025-04-02 21:29:11
     * @param out_trade_no 交易单号
     * @param total_fee  交易金额
     * @return Map
     * @Description: TODO 描述方法主要功能
     */
    @GetMapping("/createNative")
    public Map createNative(String out_trade_no, String total_fee) {
        Map<String, String> map = new HashMap<String, String>();
        //创建预下单请求对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //转换下单金额按照元
        long total = Long.parseLong(total_fee);
        BigDecimal bigTotal = BigDecimal.valueOf(total);

        BigDecimal cs = BigDecimal.valueOf(100d);

        BigDecimal bigYuan = bigTotal.divide(cs);
        System.out.println("预下单金额:" + bigYuan.doubleValue());
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + out_trade_no + "\"," +
                "    \"total_amount\":\"" + bigYuan.doubleValue() + "\"," +
                "    \"subject\":\"测试购买商品001\"," +
                "    \"store_id\":\"xa_001\"," +
                "    \"timeout_express\":\"90m\"}");//设置业务参数
        //发出预下单业务请求
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            //从相应对象读取相应结果
            String code = response.getCode();
            System.out.println("响应码:" + code);
            //全部的响应结果
            String body = response.getBody();
            System.out.println("返回结果:" + body);

            if (code.equals("10000")) {
                map.put("qrcode", response.getQrCode());
                map.put("out_trade_no", response.getOutTradeNo());
                map.put("total_fee", total_fee);
                System.out.println("qrcode:" + response.getQrCode());
                System.out.println("out_trade_no:" + response.getOutTradeNo());
                System.out.println("total_fee:" + total_fee);
            } else {
                System.out.println("预下单接口调用失败:" + body);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("/queryPayStatus")
    public BaseResult queryPayStatus(String out_trade_no) {
        int x = 0;
        BaseResult result = null;

        while (true) {
            try {
                // 调用查询接口
                Map<String, String> map = queryPayStatus2(out_trade_no);

                if (map == null) {
                    result = BaseResult.error(CodeEnum.SERVER_ERROR);
                    break;
                }

                // 解析支付宝响应
                String responseStr = map.get("response");
                if (responseStr != null) {
                    JSONObject responseJson = JSONObject.parseObject(responseStr);
                    JSONObject alipayResponse = responseJson.getJSONObject("alipay_trade_query_response");

                    if (alipayResponse != null) {
                        String code = alipayResponse.getString("code");
                        String tradeStatus = alipayResponse.getString("trade_status");

                        if ("10000".equals(code)) {
                            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                                // 支付成功
                                String tradeNo = alipayResponse.getString("trade_no");
                                String totalAmount = alipayResponse.getString("total_amount");

                                // 更新订单状态
                                //orderService.updateOrderStatus(out_trade_no, tradeNo, totalAmount);
                                result = BaseResult.ok(map);
                                break;
                            } else if ("TRADE_CLOSED".equals(tradeStatus)) {
                                result = BaseResult.ok("未付款交易超时关闭，或支付完成后全额退款");
                                break;
                            } else if ("TRADE_FINISHED".equals(tradeStatus)) {
                                result = BaseResult.ok("交易结束，不可退款");
                                break;
                            }
                        } else {
                            // 查询失败
                            result = BaseResult.error(CodeEnum.SERVER_ERROR);
                            break;
                        }
                    }
                }

                // 等待3秒后继续查询
                Thread.sleep(3000);

                // 检查是否超时（5分钟）
                x++;
                if (x >= 20) {
                    result = BaseResult.error(CodeEnum.QR_CODE_TIME_OUT);
                    break;
                }

            } catch (Exception e) {
                e.printStackTrace();
                result = BaseResult.error(CodeEnum.SERVER_ERROR);
                break;
            }
        }

        return result;
    }

    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        try {
            // 1. 获取支付宝发送的支付结果参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }

            // 2. 验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    publicKey,
                    "UTF-8",
                    "RSA2"
            );

            if (signVerified) {
                // 3. 获取交易状态
                String tradeStatus = params.get("trade_status");

                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    // 4. 获取订单信息
                    String outTradeNo = params.get("out_trade_no");
                    String tradeNo = params.get("trade_no");
                    String totalAmount = params.get("total_amount");

                    // 5. 更新订单状态
                    //orderService.updateOrderStatus(outTradeNo, tradeNo, totalAmount);

                    // 6. 调用AI推荐接口
                    // TODO: 实现AI推荐逻辑

                    return "success";
                }
            }
            return "fail";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    public Map<String, String> queryPayStatus2(String out_trade_no) {
        Map<String, String> map = new HashMap<String, String>();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + out_trade_no + "\"," +
                "    \"trade_no\":\"\"}"); //设置业务参数
        //发出请求
        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            String code = response.getCode();
            System.out.println("返回值1:===================================================" + response.getBody());
            if (code.equals("10000")) {
                System.out.println("返回值2:======================================" + response.getBody());
                map.put("out_trade_no", out_trade_no);
                map.put("tradestatus", response.getTradeStatus());
                map.put("trade_no", response.getTradeNo());
                map.put("response", response.getBody());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }


}
